package edu.jxufe.nb112.common.security.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Collection;

/**
 * Created by lvxi on 2017/11/19.
 * Note:
 */
public class RedisSessionDAO extends AbstractSessionDAO {
    private static final Logger LOG = LoggerFactory.getLogger(RedisSessionDAO.class.getName());
    private ShiroRedisCacheManager redisCacheManager;
    private String cacheName;

    private ShiroRedisCache getCache(){
        return (ShiroRedisCache)redisCacheManager.getCache(cacheName);
    }

    private void saveSession(Session session) throws UnknownSessionException{
        if(session==null){
            LOG.error("session is null");
            throw new UnknownSessionException("session is null");
        }
        getCache().put(session.getId(),session);
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        this.saveSession(session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session s = (Session) this.getCache().get(sessionId);
        return s;
    }

    public void update(Session session) throws UnknownSessionException {
        this.saveSession(session);
    }

    public void delete(Session session) {
        if(session==null){
            LOG.error("session is null");
            throw new UnknownSessionException("session is null");
        }
        this.getCache().remove(session.getId());
    }

    public Collection<Session> getActiveSessions() {
        ShiroRedisCache cache = getCache();
        Collection<Session> sessions = (Collection<Session>) cache.values();
        return sessions;
    }

    public ShiroRedisCacheManager getRedisCacheManager() {
        return redisCacheManager;
    }

    public void setRedisCacheManager(ShiroRedisCacheManager redisCacheManager) {
        this.redisCacheManager = redisCacheManager;
    }

    public String getCacheName() {
        return cacheName;
    }

    public void setCacheName(String cacheName) {
        this.cacheName = cacheName;
    }

}
